(function () {
    var config = {
        username: {
            head: '手机号码',
            txt: '请输入正确的手机号码',
            reg: function(val){
                return !new RegExp(/^((13|14|15|17|18)[0-9]{1}\d{8})$/).test(val)
            }
        },
        pass: {
            head: '密码',
            txt: '请输入正确的密码',
            reg: function(val){
                return val.length!==6
            }
        },
        nextPass: {
            head: '再次密码',
            txt: '请输入一致的密码',
            reg: function(val, regVal){
                return val !== regVal
            }
        }
    }
    var vueValidate = {}
    var errorsNum = 0
    var show = function (el, txt) {
        el.nextElementSibling.innerHTML = txt
        el.nextElementSibling.style.display = 'block'
        setTimeout(function () {
            el.nextElementSibling.style.display = 'none'
        },1500)
        errorsNum++
    }
    var require = function (name, el, val) {
        // 1，只为必填 2，只为其他 3，必填和其他
        if (el.className.indexOf('require') !== -1) {
            if (val.length === 0) {
                show(el, config[name].head + '不能为空')
                return 'stop'
            } else {
                return 'goon'
            }
        } else {
            // 不必填的话下一步不操作
            if (val.length === 0) {
                return 'stop'
            }
        }
    }
    var blurFn = function (name, val, el) {
        if (require(name, el, val) !== 'stop') {
            if (config[name].reg(val)) {         // 如果没有通过就执行显示函数
                show(el, config[name].txt)
            }
        }
    }
    vueValidate.install = function (Vue) {
        Vue.directive('myValidate', {
            acceptStatement: true,
            inserted: function (el, binding) {
                el.addEventListener('blur', function () {
                    blurFn(binding.expression, el.value, el)
                })
            }
        })
        Vue.prototype.valiDateAll = (root) => {
            var validateEles = root.querySelectorAll('.myValidate')
            errorsNum = 0   // 清零
            for (var i=0;i<validateEles.length;i++) {
            	var element = validateEles[i]
            	var name = element.name
                var val = element.value
                blurFn(name, val, element)
            }
            if (errorsNum === 0) {
                return true
            } else {
                return false
            }
        }
    }
    module.exports = vueValidate;
})()